//
//  PackageSKUView.m
//  BaseProject
//
//  Created by 王洋 on 2021/5/10.
//  Copyright © 2021 王洋. All rights reserved.
//

#import "ZZLayout.h"
#import "ORSKUDataFilter.h"
#import "SearchSectionHeader.h"
#import "PackageSKUCell.h"
#import "PackageSKUCell.h"
#import "PackageSKUDataHelper.h"

#import "PackageSKUView.h"

@interface PackageSKUView ()<UICollectionViewDelegate, UICollectionViewDataSource, ZZLayoutDelegate, UITextFieldDelegate, ORSKUDataFilterDataSource>

@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, strong) NSArray *skuData;;
@property (nonatomic, strong) ORSKUDataFilter *filter;
@property (nonatomic, strong) NSMutableArray <NSIndexPath *>*selectedIndexPaths;;

@property (nonatomic, strong) WeddingCarSpecModel *selModel;
@property (nonatomic, assign) NSInteger followCarNum;

@property (nonatomic, assign) BOOL isfinish;

@end

@implementation PackageSKUView

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.intentionBtn.layer.cornerRadius = 12.0f;
    self.skuImageView.layer.cornerRadius = 8.0f;
    self.noticeLab.hidden = YES;
    
    [self layout];
}

- (void)fillSkuViewWithModel:(CommonPackageModel *)model Type:(PackageSKUViewActionType)type {
    
    self.type = type;
    self.model = model;
    [self prepareDataWithModel:model];
}

- (void)prepareDataWithModel:(CommonPackageModel *)model {
        
    _dataSource = [PackageSKUDataHelper cacheSKUDataSourceWithModel:model].mutableCopy;
    _selectedIndexPaths = [NSMutableArray array];
    _skuData = [PackageSKUDataHelper cacheSKUDataWithModel:model].mutableCopy;
    
    _filter = [[ORSKUDataFilter alloc] initWithDataSource:self];
    _filter.needDefaultValue = YES;
    [self.collectionview reloadData]; //更新UI显示
    [self action_complete:nil];       //更新结果查询
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.cartBtn pp_clipCorners:UIRectCornerTopLeft|UIRectCornerBottomLeft radius:self.cartBtn.frame.size.height/2 border:1 color:UIColorHex(0xFF9D43)];
        
        [self.handleBtn pp_clipCorners:UIRectCornerTopRight|UIRectCornerBottomRight radius:self.handleBtn.frame.size.height/2];
        
        [self.cutBtn pp_clipCorners:UIRectCornerTopLeft|UIRectCornerBottomLeft radius:self.cutBtn.frame.size.height/2 border:1 color:UIColorHex(0xe4e4e4)];
        
        [self.addBtn pp_clipCorners:UIRectCornerTopRight|UIRectCornerBottomRight radius:self.addBtn.frame.size.height/2 border:1 color:UIColorHex(0xe4e4e4)];

        [self pp_clipCorners:UIRectCornerTopLeft|UIRectCornerTopRight radius:10];
        
    });
}

- (IBAction)cutAction:(id)sender {
    if (!self.isfinish) {
        [SVProgressHUD showInfoWithStatus:@"请选择完整属性"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    //减少数量
    if (self.followCarNum >= 1) {
        self.followCarNum--;
    }
    [self fillWithModel:self.selModel];
}

- (IBAction)addAction:(id)sender {
    //增加数量
    if (!self.isfinish) {
        [SVProgressHUD showInfoWithStatus:@"请选择完整属性"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    self.followCarNum++;
    [self fillWithModel:self.selModel];
}

- (IBAction)cartAction:(id)sender {
    
    if (!self.isfinish) {
        return;
    }
    
    self.selModel.followCarNum = self.followCarNum;
    if (self.PackageSKUViewBlock) {
        self.PackageSKUViewBlock(PackageSKUViewActionType_cart,self.selModel);
    }
}

- (IBAction)handleAction:(id)sender {
    if (!self.isfinish) {
        return;
    }
    
    self.selModel.followCarNum = self.followCarNum;
    if (self.PackageSKUViewBlock) {
        self.PackageSKUViewBlock(PackageSKUViewActionType_buy,self.selModel);
    }
}

- (IBAction)closeAction:(id)sender {
    if (self.PackageSKUViewBlock) {
        self.PackageSKUViewBlock(PackageSKUViewActionType_close,self.selModel);
    }
}


- (void)action_complete:(id)sender {
    
    NSDictionary *dic = _filter.currentResult;

    if (dic == nil) {
        NSLog(@"请选择完整 属性");
        self.skuPriceLab.text = @"请选择完整属性";
        self.isfinish = NO;
        [self.handleBtn setTitle:@"无法购买" forState:UIControlStateNormal];
        self.followCarLab.text = @"";
        return;
    }
    self.isfinish = YES;
    [self.handleBtn setTitle:@"立即预定" forState:UIControlStateNormal];

    //这里的store为skuid    是用来匹配的
    NSLog(@"选择的最终结果为=====%@",dic[@"store"]);
    NSString * sgcsId  = dic[@"store"];
    
    for (WeddingCarSpecModel *specModel in self.model.sellerGoodsCarSpecsList) {
        if ([specModel.sgcsId isEqualToString:sgcsId]) {
            self.selModel = specModel;
        }
    }
    
    //拿到结果拿到对应spcnName
    //根据spcname匹配数组userShoppingCarDetailList
    self.selModel.userShoppingCarDetailList = @[].mutableCopy;
    self.selModel.userShoppingCarDetailList = [PackageSKUDataHelper matchingSkuListFromModel:self.model withString:self.selModel.specName];
    
    [self fillWithModel:self.selModel];
}

- (void)fillWithModel:(WeddingCarSpecModel *)model {
        
    //如果是套餐的时候
    if ([self.model.goodsMold isEqualToString:@"1"]) {
        if (self.followCarNum < model.followCarNum) {
            self.noticeLab.hidden = NO;
        } else {
            self.noticeLab.hidden = YES;
        }
        self.followCarLab.hidden = NO;
        self.carTagLab.text = @"跟车数量";
    }else if ([self.model.goodsMold isEqualToString:@"3"]) {
        self.noticeLab.hidden = YES;
        self.followCarLab.hidden = YES;
        self.carTagLab.text = @"车数量";
    }
    
    self.followCarLab.text = [NSString stringWithFormat:@"套餐内跟车数量：%ld辆",(long)model.followCarNum];
    
    //如果是单品的时候
    if (!self.followCarNum) {
        self.followCarNum = self.selModel.followCarNum;
    }
    
    //如果没加减     就赋值默认的
    //如果有加减     赋值加减的数字
    
    self.countTF.text = [NSString stringWithFormat:@"%ld",(long)self.followCarNum];
    
    self.selSKULab.text = [NSString stringWithFormat:@"已选：%@",model.specName];
    
    //检查默认带几个跟车  如果输入框跟车数量大于默认跟车数量   数值要加
    
    double platformPrice = model.platformPrice;
    double marketPrice = model.marketPrice;
    
    if ([self.model.goodsMold isEqualToString:@"1"]) {

        if (self.followCarNum > model.followCarNum) {
            platformPrice = model.platformPrice + (self.followCarNum - model.followCarNum)*model.followCarPrice;
            marketPrice = model.marketPrice + (self.followCarNum - model.followCarNum)*model.followCarPrice;
        } else {
            platformPrice = model.platformPrice;
            marketPrice = model.marketPrice;
        }
        
    } else if ([self.model.goodsMold isEqualToString:@"3"]) {

        platformPrice = model.platformPrice * self.followCarNum;
        marketPrice = model.marketPrice *self.followCarNum ;
        
    }
    
    self.selModel.totalPrice = platformPrice;
    self.skuPriceLab.text = [NSString stringWithFormat:@"¥%@",[Utilities changeDoubleToString:platformPrice]];
//    self.skuLinePriceLab.text = [NSString stringWithFormat:@"市场价¥%@",[Utilities changeDoubleToString:marketPrice]];
    [self.skuImageView sd_setImageWithURL:[NSURL URLWithString:model.specImage]];
    
    
    NSDictionary*attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
    NSMutableAttributedString*attribtStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"¥%@",[NSString stringWithFormat:@"市场价¥%@",[Utilities changeDoubleToString:marketPrice]]] attributes:attribtDic];//
    self.skuLinePriceLab.attributedText = attribtStr;
    
    
    NSInteger depositType = self.model.sellerDeposit.depositType;
    double deposit = self.model.sellerDeposit.deposit;
    double intentionMoney = 0;
    if (depositType == 1) {
        double dep = deposit*0.01;
        intentionMoney = dep * platformPrice;
    } else {
        intentionMoney = deposit;
    }
    [self.intentionBtn setTitle:[NSString stringWithFormat:@"意向金¥%@",[Utilities changeDoubleToString:intentionMoney]] forState:UIControlStateNormal];
    
    if (deposit == 0) {
        self.intentionBtn.hidden = YES;
    } else {
        self.intentionBtn.hidden = NO;
    }
    
}

- (void)layout {
        
    ZZLayout *layout = [[ZZLayout alloc] initWith:ZZLayoutFlowTypeAutomateFloat delegate:self];

    _collectionview.collectionViewLayout = layout;
    _collectionview.delegate = self;
    _collectionview.dataSource = self;
    
    //注册cell
    [_collectionview registerNib:[UINib nibWithNibName:@"PackageSKUCell" bundle:nil] forCellWithReuseIdentifier:@"PackageSKUCellID"];
    [_collectionview registerNib:[UINib nibWithNibName:@"SearchSectionHeader" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SearchSectionHeader"];
    [_collectionview registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter"];
    _collectionview.showsHorizontalScrollIndicator = NO;
    _collectionview.bounces = YES;
    if (@available(iOS 11.0, *)) {
        _collectionview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    _collectionview.backgroundColor = [UIColor whiteColor];

}

#pragma mark- 协议方法
//collectionView的协议方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [_filter didSelectedPropertyWithIndexPath:indexPath];
    [self.collectionview reloadData];
    [self action_complete:nil];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    PackageSKUCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PackageSKUCellID" forIndexPath:indexPath];
//    [cell fillCellWithModel:self.dataArray[indexPath.row]];
    
    NSArray *data = _dataSource[indexPath.section][@"value"];
    cell.skuNameLab.text = data[indexPath.row];
    
    if ([_filter.availableIndexPathsSet containsObject:indexPath]) {
        [cell setCellType:PackageSKUSelType_nor];
    }else {
        [cell setCellType:PackageSKUSelType_stop];
    }
    
    if ([_filter.selectedIndexPaths containsObject:indexPath]) {
        [cell setCellType:PackageSKUSelType_sel];
    }
    
    return cell;
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [_dataSource[section][@"value"] count];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return _dataSource.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *reusableView = nil;
    // 区头
    if (kind == UICollectionElementKindSectionHeader) {
        SearchSectionHeader *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SearchSectionHeader" forIndexPath:indexPath];
        
        headerView.sectionTitle.text = _dataSource[indexPath.section][@"name"];
        headerView.sectionBtn.hidden = YES;
        
        reusableView = headerView;
    }
    // 区尾
    if (kind == UICollectionElementKindSectionFooter) {
        UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter" forIndexPath:indexPath];
        reusableView = footerView;
    }
    return reusableView;
}

//ZZLyout的流协议方法
- (CGFloat)layout:(ZZLayout *)layout heightForRowAtIndexPath:(NSIndexPath *)indexPath {//返回item的度
    return 26;//同一section下请不要改变高度.
}

- (CGFloat)layout:(ZZLayout *)layout widthForRowAtIndexPath:(NSIndexPath *)indexPath {//返回item的宽
    
    NSArray *data = _dataSource[indexPath.section][@"value"];

    return [Utilities getStringWidthWithString:data[indexPath.row] fontSize:12 andHeight:35] + 30;//这里可以根据内容传入任意宽度
//    return 100;
    
}

- (UIEdgeInsets)layout:(ZZLayout *)layout insetForSectionAtIndex:(NSInteger)section {//设置每个区的边距
    return UIEdgeInsetsMake(10, 15, 10, 15);
}

- (NSInteger)layout:(ZZLayout *)layout lineSpacingForSectionAtIndex:(NSInteger)section {//设置每个区的行间距
    return 10;
}

- (CGFloat) layout:(ZZLayout *)layout interitemSpacingForSectionAtIndex:(NSInteger)section {//设置每个区的列间距
    return 15;
}

- (CGSize)layout:(ZZLayout *)layout referenceSizeForHeaderInSection:(NSInteger)section {//设置区头的高度
    return CGSizeMake(TTScreenWidth, 44);
}

- (UIColor *)layout:(UICollectionView *)layout colorForSection:(NSInteger)section {
    return [UIColor whiteColor];
}

#pragma mark -- ORSKUDataFilterDataSource

- (NSInteger)numberOfSectionsForPropertiesInFilter:(ORSKUDataFilter *)filter {
    return _dataSource.count;
}

- (NSArray *)filter:(ORSKUDataFilter *)filter propertiesInSection:(NSInteger)section {
    return _dataSource[section][@"value"];
}

- (NSInteger)numberOfConditionsInFilter:(ORSKUDataFilter *)filter {
    return _skuData.count;
}

- (NSArray *)filter:(ORSKUDataFilter *)filter conditionForRow:(NSInteger)row {
    NSString *condition = _skuData[row][@"contition"];
    return [condition componentsSeparatedByString:@","];
}

- (id)filter:(ORSKUDataFilter *)filter resultOfConditionForRow:(NSInteger)row {
    NSDictionary *dic = _skuData[row];
    return @{@"price": dic[@"price"],
             @"store": dic[@"store"]};
}

@end
